const User = require('../models/User');

const getAllUsersService = async (params) => {
    try {
        const where = {};
        let page = 1;
        let pageSize = 10;

        if (params) {
            if (params.username) {
                where.username = params.username;
            }
            if (params.phone_number) {
                where.phone_number = params.phone_number;
            }
            if (params.page) {
                page = parseInt(params.page, 10);
            }
            if (params.pageSize) {
                pageSize = parseInt(params.pageSize, 10);
            }
        }

        const offset = (page - 1) * pageSize;
        const limit = pageSize;

        const { count, rows } = await User.findAndCountAll({
            where: where,
            attributes: ['id', 'phone_number', 'email', 'address', 'birthday', 'real_name', 'sex', 'username'],
            offset: offset,
            limit: limit,
            order: [['id', 'DESC']]
        });

        return {
            total: count,
            list: rows,
            page: page,
            pageSize: pageSize
        };
    } catch (err) {
        throw new Error(`Error in getAllUsersService: ${err.message}`);
    }
};

const getUserById = async (userId) => {
    try {
        const user = await User.findByPk(userId, {
            attributes: ['id', 'username', 'email'], // 排除密码字段
        });
        if (!user) {
            console.log('User not found'); // 添加日志
            throw new Error('User not found');
        }
        return user;
    } catch (err) {
        throw err;
    }
};

// 通过username查询用户信息
const getUserByUsername = async (username) => {
    try {
        const user = await User.findOne({
            where: { username: username }, // 传递查询条件
            attributes: ['id', 'username', 'password'], // 只选择需要的字段
        });
        // 如果没有找到用户
        if (!user) {
            console.log('User not found'); // 添加日志
            throw new Error('User not found');
        }

        return user;  // 返回找到的用户
    }
    catch (err) {
        // 捕获并重新抛出错误
        throw new Error(`Error in getUserByUsername: ${err.message}`);
    }
};

const addUser = async (user) => {
    try {
        const newUser = await User.create(user);
        return newUser;
    } catch (err) {
        throw new Error(`Error in addUser: ${err.message}`);
    }
};

const updateUser = async (userId, user) => {
    try {
        const existingUser = await User.findByPk(userId);
        if (!existingUser) {
            throw new Error('User not found');
        }
        await existingUser.update(user);
        return existingUser;
    } catch (err) {
        throw new Error(`Error in updateUser: ${err.message}`);
    }
};

const deleteUserService = async (userId) => {
    try {
        const existingUser = await User.findByPk(userId);
        if (!existingUser) {
            throw new Error('User not found');
        }
        await existingUser.destroy();
        return true;
    } catch (err) {
        throw new Error(`Error in deleteUser: ${err.message}`);
    }
};

module.exports = {
    getUserById,
    getUserByUsername,
    getAllUsersService,
    addUser,
    updateUser,
    deleteUserService
};